/**
 * HTTP请求工具
 */
import axios, { AxiosInstance, InternalAxiosRequestConfig, AxiosResponse } from 'axios';
import { ElMessage, ElLoadingService } from 'element-plus';
import constant from './constant';
import TokenManager from './tokenManager';

// 创建axios实例 - SSO增强版
const axiosInstance: AxiosInstance = axios.create({
  baseURL: constant.baseURL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  },
  withCredentials: true,  // 🔥 SSO关键：允许携带Cookie（跨域请求）
});

// 请求拦截器
axiosInstance.interceptors.request.use(
  async (config: InternalAxiosRequestConfig) => {
    const tokenManager = TokenManager.getInstance();
    const token = TokenManager.getAuthToken();
    
    // 如果是刷新token的请求，直接通过
    if (config.url?.includes('/auth-center/refresh-token')) {
      return config;
    }

      // 如果有token，检查是否过期
      if (token) {
        // 如果token过期了，需要刷新
        if (TokenManager.isTokenExpired()) {
          // 如果已经在刷新过程中，等待刷新完成
          if (tokenManager.isRefreshingToken()) {
            return new Promise<InternalAxiosRequestConfig>((resolve) => {
            tokenManager.addRefreshSubscriber((newToken: string) => {
              config.headers.Authorization = `Bearer ${newToken}`;
              resolve(config);
            });
          });
        } else {
          // 开始刷新token
          const newToken = await tokenManager.refreshToken();
          
          if (newToken) {
            config.headers.Authorization = `Bearer ${newToken}`;
          } else {
            // 刷新失败，清除认证信息
            TokenManager.clearAuth();
            console.error('[HTTP Request] 刷新Token失败，已清除认证信息');
          }
        }
        } else {
          // token未过期，正常添加到请求头
          config.headers.Authorization = `Bearer ${token}`;
        }
      }
    
    return config;
  },
  (error: any) => {
    console.error('[HTTP Request Error]', error);
    return Promise.reject(error);
  }
);

// 响应拦截器
axiosInstance.interceptors.response.use(
  (response: AxiosResponse) => {
    // 如果响应包含新的token，更新localStorage
    if (response.data && response.data.data) {
      if (response.data.data.accessToken) {
        TokenManager.setAuthToken(response.data.data.accessToken);
      }
      if (response.data.data.refreshToken) {
        TokenManager.setRefreshToken(response.data.data.refreshToken);
      }
    }
    
    return response;
  },
  async (error: any) => {
    console.error('[HTTP Response Error]', error);
    
    const originalRequest = error.config;
    const tokenManager = TokenManager.getInstance();
    
    // 如果是401错误且没有重试过，尝试刷新token
    if (error.response?.status === 401 && !originalRequest._retry) {
      originalRequest._retry = true;
      
      // 如果已经在刷新过程中，等待刷新完成
      if (tokenManager.isRefreshingToken()) {
        return new Promise((resolve, reject) => {
          tokenManager.addRefreshSubscriber((newToken: string) => {
            if (originalRequest.headers) {
              originalRequest.headers.Authorization = `Bearer ${newToken}`;
            }
            resolve(axiosInstance(originalRequest));
          });
        });
      }
      
      const refreshToken = TokenManager.getRefreshToken();
      if (refreshToken) {
        try {
          const newToken = await tokenManager.refreshToken();
          
          if (newToken) {
            // 重试原请求
            if (originalRequest.headers) {
              originalRequest.headers.Authorization = `Bearer ${newToken}`;
            }
            return axiosInstance(originalRequest);
          }
        } catch (refreshError: any) {
          console.error('[HTTP] Token刷新失败', refreshError);
          TokenManager.clearAuth();
        }
      }
    }
    
    return Promise.reject(error);
  }
);

// 请求配置接口
interface RequestConfig {
  showLoading?: boolean;
  showError?: boolean;
  showSuccess?: boolean;
  successMsg?: string;
}

// 默认配置
const defaultConfig: RequestConfig = {
  showLoading: false,
  showError: true,
  showSuccess: false
};

/**
 * 创建请求方法
 * @param method HTTP方法
 * @returns 请求函数
 */
const createRequest = (method: string) => {
  return async (url: string, data: any = {}, config: RequestConfig = {}) => {
    // 合并配置
    const mergedConfig = { ...defaultConfig, ...config };
    const { showLoading, showError, showSuccess, successMsg } = mergedConfig;
    
    // 显示加载提示
    let loadingInstance: any = null;
    if (showLoading) {
      loadingInstance = ElLoadingService({
        lock: true,
        text: '处理中...',
        background: 'rgba(0, 0, 0, 0.7)'
      });
    }
    
    try {
      const axiosConfig: any = { method, url };
      
      // 根据请求方法设置参数
      if (['get', 'delete'].includes(method)) {
        axiosConfig.params = data;
      } else {
        axiosConfig.data = data;
      }
      
      // 发送请求
      const response = await axiosInstance(axiosConfig);
      
      // 关闭加载提示
      if (loadingInstance) {
        loadingInstance.close();
      }
      
      // 显示成功提示
      if (showSuccess && response.data.code === 200) {
        ElMessage.success(successMsg || response.data.message || '操作成功');
      }
      
      return response.data;
    } catch (error: any) {
      // 关闭加载提示
      if (loadingInstance) {
        loadingInstance.close();
      }
      
      // 特定API路径的403错误静默处理
      const silentErrorPaths = [
        '/user/my-permissions',
        '/user/my-role-permissions',
        '/permission/menu/tree',
        '/permission/button/'
      ];
      
      const isPermissionError = error.response?.status === 403 && 
        silentErrorPaths.some(path => url.includes(path));
      
      // 显示错误提示（除非是权限相关的403错误）
      if (showError && error.response && !isPermissionError) {
        const message = error.response.data?.message || '请求失败';
        ElMessage.error(message);
      } else if (showError && !isPermissionError) {
        ElMessage.error('网络错误，请稍后重试');
      }
      
      throw error;
    }
  };
};

// 导出请求方法
const httpClient = {
  get: createRequest('get'),
  post: createRequest('post'),
  put: createRequest('put'),
  delete: createRequest('delete')
};

export default httpClient; 